<template lang="pug">
  Select.category-selector(v-model='value', :label-in-value='true', :multiple='multiple', clearable, @on-change='onChange', :size='size', :placeholder='placeholder')
    Option(v-for='item in flatCategories', :value='item.id', :key='item.id')
      //- span(:class='{ "sub": item.pid > 0 }')
      span(v-if='item.depth') {{ "--".repeat(item.depth) }}&nbsp;
      span {{ item.name }}
</template>

<script>
import { cloneDeep } from 'lodash'
import Util from '@/libs/util'
import Api from '@/apis/category'

export default {
  props: {
    defaultValue: {
      type: [String, Array]
    },
    module: {
      type: String,
      // oneOf:
      required: true
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    size: {
      type: String,
      default: 'default'
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      value: this.defaultValue ? this.defaultValue : (this.multiple ? [] : null),
      categories: []
    }
  },
  computed: {
    flatCategories () {
      // return flatMap(cloneDeep(this.categories), (item) => {
      //   if (item.children && item.children.length > 0) {
      //     const children = item.children
      //     delete item.children
      //     children.unshift(item)
      //     return children
      //   }
      //   return [item]
      // })
      return Util.flattenTree(cloneDeep(this.categories))
    }
  },
  mounted () {
    Api.getCategories({ gid: this.$store.state.app.id, moduleName: this.module })
      .then(data => (this.categories = data))
  },
  methods: {
    onChange (val) {
      // console.log(this.value, e)
      this.$emit('change', val, this.value)
    }
  }
}
</script>

<style lang="less" scoped>
.sub {
  // padding-left: 8px;

  &:before {
    content: '- ';
  }
}
</style>

<style>
.category-selector .ivu-select-dropdown {
  z-index: 1000;
}
</style>


